package cn.zwwly.community.tool;

import cn.zwwly.community.dto.AccessTokenDTO;
import cn.zwwly.community.dto.GiteeUser;
import com.alibaba.fastjson.JSON;
import okhttp3.*;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
public class OkHttp {
    public String getAccessToken(AccessTokenDTO accessTokenDTO){
        MediaType json = MediaType.get("application/json; charset=utf-8");

        OkHttpClient client = new OkHttpClient();
        
        RequestBody body = RequestBody.create(JSON.toJSONString(accessTokenDTO), json);
        Request request = new Request.Builder()
            .url("https://gitee.com/oauth/token?grant_type=authorization_code")
            .post(body)
            .build();
        try (Response response = client.newCall(request).execute()) {
            String result = response.body().string();
            String accessToken = result.split(",")[0].split(":")[1].substring(1, result.split(",")[0].split(":")[1].length()-1);
//            System.out.println(result);
            return accessToken;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
    
    public GiteeUser getUser(String accessToken){
        OkHttpClient client = new OkHttpClient();

        Request request = new Request.Builder()
                .url("https://gitee.com/api/v5/user?access_token="+accessToken)
                .build();

        try (Response response = client.newCall(request).execute()) {
            String str = response.body().string();
            GiteeUser giteeUser = JSON.parseObject(str, GiteeUser.class);
        return giteeUser;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}


//{"access_token":"cf78c92060ac8a4bf35f3164ba9a5249","token_type":"bearer","expires_in":86400,"refresh_token":"5795012f61700bd9034dd4c014e295cda62acd15c8db7b5d825c7147f38247ec","scope":"user_info emails","created_at":1599375537}